#!/bin/bash

# 日志文件
LOG_FILE="/root/allinone06.log"
USER_FILE="/root/allinone-idpw.txt"
DOMAIN=${1:-"myaimaster.zapto.org"}
EMAIL="007.aimaster@gmail.com"
BACKUP_DIR="/etc/letsencrypt/backup_$DOMAIN"

exec > >(tee -a ${LOG_FILE}) 2>&1

# Function to log and execute commands
log_and_execute() {
    echo "Executing: $@" | tee -a ${LOG_FILE}
    "$@" | tee -a ${LOG_FILE}
}

# Function to wait for dpkg lock
wait_for_dpkg_lock() {
    while sudo fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 || sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1; do
        echo "Waiting for other package management process to finish..." | tee -a ${LOG_FILE}
        sleep 5
    done
}

# Function to check Apache configuration
check_apache_config() {
    log_and_execute sudo apache2ctl configtest
    if ! sudo apache2ctl configtest | grep -q "Syntax OK"; then
        echo "There is a syntax error in the Apache configuration. Please check the output above for details." | tee -a ${LOG_FILE}
        sudo tail -n 50 /var/log/apache2/error.log | tee -a ${LOG_FILE}
        #exit 1
    fi
}

# 更新系统包信息并安装必要工具
log_and_execute sudo apt-get update
log_and_execute sudo apt-get install -y dos2unix git wget unzip certbot python3-certbot-apache ufw

# 克隆GitHub仓库
log_and_execute git clone https://github.com/eric010101/be.git /root/be

# 复制并转换配置文件格式
log_and_execute sudo cp /root/be/all20240619.ini /root/all20240619.ini
log_and_execute dos2unix /root/all20240619.ini

# 加载配置文件
CONFIG_FILE="/root/all20240619.ini"
if [[ ! -f $CONFIG_FILE ]]; then
    echo "配置文件 $CONFIG_FILE 不存在。" | tee -a ${LOG_FILE}
    #exit 1
fi

GITHUB_USERNAME=$(awk -F ' = ' '/username/ {print $2}' $CONFIG_FILE)
GITHUB_PASSWORD=$(awk -F ' = ' '/password/ {print $2}' $CONFIG_FILE)
GITHUB_REPO=$(awk -F ' = ' '/repository/ {print $2}' $CONFIG_FILE)
EMAIL=$(awk -F ' = ' '/email/ {print $2}' $CONFIG_FILE)
MYSQL_ROOT_PASSWORD=$(awk -F ' = ' '/root_password/ {print $2}' $CONFIG_FILE)
MYSQL_DATABASE=$(awk -F ' = ' '/database_name/ {print $2}' $CONFIG_FILE)
MYSQL_USER=$(awk -F ' = ' '/database_user/ {print $2}' $CONFIG_FILE)
MYSQL_PASSWORD=$(awk -F ' = ' '/database_password/ {print $2}' $CONFIG_FILE)
PHPMYADMIN_APP_PASSWORD=$(awk -F ' = ' '/app_password/ {print $2}' $CONFIG_FILE)

# 安装Apache
log_and_execute wait_for_dpkg_lock
log_and_execute sudo apt-get install -y apache2
log_and_execute sudo systemctl enable apache2
log_and_execute sudo systemctl start apache2

# 验证Apache配置
check_apache_config

# 安装MySQL
log_and_execute wait_for_dpkg_lock
log_and_execute sudo debconf-set-selections <<< "mysql-server mysql-server/root_password password $MYSQL_ROOT_PASSWORD"
log_and_execute sudo debconf-set-selections <<< "mysql-server mysql-server/root_password_again password $MYSQL_ROOT_PASSWORD"
log_and_execute sudo apt-get install -y mysql-server
log_and_execute sudo systemctl enable mysql
log_and_execute sudo systemctl start mysql

# 安装PHP并启用模块
log_and_execute wait_for_dpkg_lock
log_and_execute sudo apt-get install -y php libapache2-mod-php php-mysql
PHP_VERSION=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;")
log_and_execute sudo a2enmod php${PHP_VERSION}
log_and_execute sudo systemctl restart apache2

# 修改 PHP 配置
PHP_INI_FILE=$(php -r "echo php_ini_loaded_file();")
log_and_execute sudo sed -i "s/upload_max_filesize = .*/upload_max_filesize = 200M/" $PHP_INI_FILE
log_and_execute sudo sed -i "s/post_max_size = .*/post_max_size = 200M/" $PHP_INI_FILE
log_and_execute sudo sed -i "s/max_execution_time = .*/max_execution_time = 60/" $PHP_INI_FILE
log_and_execute sudo sed -i "s/max_input_time = .*/max_input_time = 60/" $PHP_INI_FILE
log_and_execute sudo systemctl restart apache2

# 配置防火墙
log_and_execute sudo ufw allow 'Apache Full'
log_and_execute sudo ufw reload

# 验证服务
if sudo systemctl is-active apache2 | grep -q "active"; then
    echo "Apache service is running." | tee -a ${LOG_FILE}
else
    echo "Apache service is not running. Please check the installation." | tee -a ${LOG_FILE}
fi

if sudo systemctl is-active mysql | grep -q "active"; then
    echo "MySQL service is running." | tee -a ${LOG_FILE}
else
    echo "MySQL service is not running. Please check the installation." | tee -a ${LOG_FILE}
fi

if php -v | grep -q "PHP"; then
    echo "PHP is installed." | tee -a ${LOG_FILE}
else
    echo "PHP is not installed. Please check the installation." | tee -a ${LOG_FILE}
fi

# 安装WordPress
log_and_execute wget -c http://wordpress.org/latest.tar.gz
log_and_execute tar -xzvf latest.tar.gz
log_and_execute sudo mkdir -p /var/www/html/wordpress
log_and_execute sudo cp -r wordpress/* /var/www/html/wordpress/
log_and_execute sudo chown -R www-data:www-data /var/www/html/wordpress/
log_and_execute sudo chmod -R 755 /var/www/html/wordpress/
cd /var/www/html/wordpress/
log_and_execute sudo cp wp-config-sample.php wp-config.php
log_and_execute sudo sed -i "s/database_name_here/$MYSQL_DATABASE/" wp-config.php
log_and_execute sudo sed -i "s/username_here/$MYSQL_USER/" wp-config.php
log_and_execute sudo sed -i "s/password_here/$MYSQL_PASSWORD/" wp-config.php
log_and_execute mysql -u root -p$MYSQL_ROOT_PASSWORD -e "CREATE DATABASE $MYSQL_DATABASE;"
log_and_execute mysql -u root -p$MYSQL_ROOT_PASSWORD -e "CREATE USER '$MYSQL_USER'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';"
log_and_execute mysql -u root -p$MYSQL_ROOT_PASSWORD -e "GRANT ALL PRIVILEGES ON $MYSQL_DATABASE.* TO '$MYSQL_USER'@'localhost';"
log_and_execute mysql -u root -p$MYSQL_ROOT_PASSWORD -e "FLUSH PRIVILEGES;"

# 安装phpMyAdmin
log_and_execute wait_for_dpkg_lock
log_and_execute sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/dbconfig-install boolean true"
log_and_execute sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/app-password-confirm password $PHPMYADMIN_APP_PASSWORD"
log_and_execute sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/admin-pass password $MYSQL_ROOT_PASSWORD"
log_and_execute sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/mysql/app-pass password $PHPMYADMIN_APP_PASSWORD"
log_and_execute sudo debconf-set-selections <<< "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2"
log_and_execute sudo apt-get install -y phpmyadmin

# Include phpMyAdmin configuration in Apache
if [ ! -f /etc/apache2/conf-available/phpmyadmin.conf ]; then
    log_and_execute sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
    log_and_execute sudo a2enconf phpmyadmin.conf
fi
log_and_execute sudo systemctl reload apache2

# 安装BeTheme
if [ -f /root/be/beth.zip ] && [ -f /root/be/beth-child.zip ]; then
    log_and_execute sudo unzip /root/be/beth.zip -d /var/www/html/wordpress/wp-content/themes/
    log_and_execute sudo unzip /root/be/beth-child.zip -d /var/www/html/wordpress/wp-content/themes/
    log_and_execute sudo chown -R www-data:www-data /var/www/html/wordpress/wp-content/themes/
else
    echo "BeTheme files not found, skipping installation." | tee -a ${LOG_FILE}
fi

# 复制文件到FTP上传目录
FTP_UPLOAD_DIR="/home/ftpuser/upload"
log_and_execute sudo mkdir -p $FTP_UPLOAD_DIR
if [ -f $CONFIG_FILE ]; then
    log_and_execute sudo cp $CONFIG_FILE $FTP_UPLOAD_DIR/${DOMAIN}_all20240619.ini
fi
if [ -f $LOG_FILE ]; then
    log_and_execute sudo cp $LOG_FILE $FTP_UPLOAD_DIR/${DOMAIN}_allinone06.log
fi
if [ -f $USER_FILE ]; then
    log_and_execute sudo cp $USER_FILE $FTP_UPLOAD_DIR/${DOMAIN}_allinone-idpw.txt
fi

# 安装suno API
log_and_execute sudo apt install npm -y
log_and_execute git clone https://github.com/gcui-art/suno-api.git /root/suno-api
log_and_execute cp /root/be/suno.env /root/suno-api/.env
cd /root/suno-api/
npm install

log_and_execute sudo ufw allow 3000
log_and_execute sudo ufw reload
log_and_execute sudo ufw status

# 安装suno Web
log_and_execute git clone https://github.com/eric010101/sunoweb.git /var/www/html/wordpress/suno

echo "Apache configuration fixed and reloaded successfully." | tee -a ${LOG_FILE}
echo "LAMP stack, phpMyAdmin, WordPress, and BeTheme installation and configuration completed." | tee -a ${LOG_FILE}
echo "SSL certificate has been obtained for $DOMAIN." | tee -a ${LOG_FILE}
echo "Please change 'rootpassword', '$MYSQL_DATABASE', '$MYSQL_USER', and '$MYSQL_PASSWORD' to secure values of your choice." | tee -a ${LOG_FILE}
echo "You can access your WordPress site at https://$DOMAIN/wordpress" | tee -a ${LOG_FILE}
echo "You can access phpMyAdmin at https://$DOMAIN/phpmyadmin" | tee -a ${LOG_FILE}

# 日志文件
LOG_FILE="/root/generate-ssl-certificate.log"
exec > >(tee -a ${LOG_FILE}) 2>&1
exec 2> >(tee -a ${LOG_FILE} >&2)

# 记录命令执行到日志
log_and_execute() {
    echo "Executing: $@" | tee -a ${LOG_FILE}
    "$@"
}

# 设置 ServerName 指令
log_and_execute sudo bash -c "echo 'ServerName $DOMAIN' >> /etc/apache2/apache2.conf"

# 注释掉 default-ssl.conf 中的SSLCertificateFile配置
log_and_execute sudo sed -i 's|^\(SSLCertificateFile\)|#\1|' /etc/apache2/sites-available/default-ssl.conf
log_and_execute sudo sed -i 's|^\(SSLCertificateKeyFile\)|#\1|' /etc/apache2/sites-available/default-ssl.conf

# 停止Apache服务
log_and_execute sudo systemctl stop apache2

# 生成新的HTTPS证书
#log_and_execute sudo certbot certonly --standalone -d $DOMAIN --non-interactive --agree-tos --email $EMAIL

# 生成新的HTTPS证书
log_and_execute sudo certbot certonly --standalone -d $DOMAIN --non-interactive --agree-tos --email $EMAIL --force-renewal


# 确定最新的证书目录（处理可能的-0001，-0002等情况）
latest_dir=$(ls -dt /etc/letsencrypt/live/$DOMAIN* | head -1)
CERT_PATH="$latest_dir/fullchain.pem"
KEY_PATH="$latest_dir/privkey.pem"

# 检查证书文件
if [ -f "$CERT_PATH" ] && [ -f "$KEY_PATH" ]; then
    echo "证书生成成功。" | tee -a ${LOG_FILE}
else
    echo "证书生成失败，请检查日志。" | tee -a ${LOG_FILE}
    exit 1
fi

# 配置Apache使用新的证书
log_and_execute sudo bash -c "cat > /etc/apache2/sites-available/default-ssl.conf" <<EOF
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
    ServerAdmin webmaster@localhost
    ServerName $DOMAIN
    DocumentRoot /var/www/html/wordpress

    ErrorLog \${APACHE_LOG_DIR}/error.log
    CustomLog \${APACHE_LOG_DIR}/access.log combined

    SSLEngine on
    SSLCertificateFile $CERT_PATH
    SSLCertificateKeyFile $KEY_PATH
    Include /etc/letsencrypt/options-ssl-apache.conf

    <FilesMatch "\\.(cgi|shtml|phtml|php)\$">
        SSLOptions +StdEnvVars
        SetHandler application/x-httpd-php
    </FilesMatch>

    <Directory /usr/lib/cgi-bin>
        SSLOptions +StdEnvVars
    </Directory>

    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    BrowserMatch "MSIE [2-6]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
    BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>
</IfModule>
EOF

# 创建和配置 /etc/letsencrypt/options-ssl-apache.conf 文件
echo "Creating and configuring /etc/letsencrypt/options-ssl-apache.conf"
sudo rm -f /etc/letsencrypt/options-ssl-apache.conf
sudo mkdir -p /etc/letsencrypt
sudo bash -c "cat > /etc/letsencrypt/options-ssl-apache.conf" <<EOF
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite HIGH:!aNULL:!MD5
SSLHonorCipherOrder on
EOF

# 配置HTTP到HTTPS的重定向
log_and_execute sudo bash -c "cat > /etc/apache2/sites-available/000-default.conf" <<EOF
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName $DOMAIN
    DocumentRoot /var/www/html

    ErrorLog \${APACHE_LOG_DIR}/error.log
    CustomLog \${APACHE_LOG_DIR}/access.log combined

    # Redirect HTTP to HTTPS
    Redirect "/" "https://$DOMAIN/"
</VirtualHost>
EOF

sudo apache2ctl configtest

# 确保防火墙允许80和443端口
log_and_execute sudo ufw allow 80
log_and_execute sudo ufw allow 443
log_and_execute sudo ufw allow 1080
log_and_execute sudo ufw allow 8080
log_and_execute sudo ufw allow 23322
log_and_execute sudo ufw reload

log_and_execute sudo apache2ctl configtest

# 启用站点配置并重新加载Apache服务
log_and_execute sudo a2enmod ssl
log_and_execute sudo a2ensite 000-default
log_and_execute sudo a2ensite default-ssl
log_and_execute sudo systemctl reload apache2
log_and_execute sudo systemctl restart apache2
log_and_execute sudo systemctl start apache2

# 检查Apache配置并重新启动服务
if log_and_execute sudo apache2ctl configtest | grep -q "Syntax OK"; then
    log_and_execute sudo systemctl reload apache2
	log_and_execute sudo systemctl start apache2
else
    echo "Apache配置有错误，请检查日志。" | tee -a ${LOG_FILE}
    #exit 1
fi

echo "HTTPS证书生成和配置完成。" | tee -a ${LOG_FILE}
echo "请访问 https://$DOMAIN 以验证配置。" | tee -a ${LOG_FILE}

# 自动检测服务器的外部IP地址
SERVER_IP=$(curl -4 -s http://ipv4.icanhazip.com)

# 更新并安装必要的软件包

# 下载并安装V2Ray
V2RAY_VERSION=$(curl -s https://api.github.com/repos/v2fly/v2ray-core/releases/latest | grep 'tag_name' | cut -d\" -f4)
curl -L -o v2ray.zip https://github.com/v2fly/v2ray-core/releases/download/${V2RAY_VERSION}/v2ray-linux-64.zip
unzip v2ray.zip -d /usr/local/bin/
rm v2ray.zip

# 创建V2Ray配置文件目录
sudo mkdir -p /usr/local/etc/v2ray

# 创建V2Ray配置文件
UUID='69a2406a-f1a4-4bde-ac73-d088d53d4b22'
#UUID=$(uuidgen)
sudo tee /usr/local/etc/v2ray/config.json > /dev/null <<EOF
{
  "inbounds": [{
    "port": 1080,
    "listen": "0.0.0.0",
    "protocol": "vmess",
    "settings": {
      "clients": [{
        "id": "${UUID}",
        "alterId": 0
      }]
    }
  }],
  "outbounds": [{
    "protocol": "freedom",
    "settings": {}
  }]
}
EOF

# 创建V2Ray服务文件
sudo tee /etc/systemd/system/v2ray.service > /dev/null <<EOF
[Unit]
Description=V2Ray Service
After=network.target

[Service]
ExecStart=/usr/local/bin/v2ray run -config /usr/local/etc/v2ray/config.json
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

# 启动并启用V2Ray服务
sudo systemctl daemon-reload
sudo systemctl start v2ray
sudo systemctl enable v2ray

# 配置防火墙，允许1080端口
sudo ufw allow 1080/tcp
sudo ufw enable

# 输出配置信息到/root/v2ray_info.txt
sudo tee /root/v2ray_info.txt > /dev/null <<EOF
V2Ray服务器已安装并运行。请在V2rayN客户端中使用以下配置信息：

服务器地址：${SERVER_IP}
端口：1080
UUID：${UUID}
额外ID：0
传输协议：TCP
EOF

# 显示完成信息
echo "配置文件已保存到 /root/v2ray_info.txt"
echo "你可以通过以下命令下载该文件："
echo "scp root@${SERVER_IP}:/root/v2ray_info.txt ."

# 确保所有必要服务在启动时自动启动
SERVICES=("apache2" "mysql" "php${PHP_VERSION}-fpm" "ufw" "suno-api")

for SERVICE in "${SERVICES[@]}"; do
    log_and_execute sudo systemctl enable $SERVICE
    log_and_execute sudo systemctl start $SERVICE
done

# 检查并修复Apache配置
check_apache_config

# 重新加载防火墙规则
log_and_execute sudo ufw reload

# 验证服务状态
for SERVICE in "${SERVICES[@]}"; do
    if sudo systemctl is-active $SERVICE | grep -q "active"; then
        echo "$SERVICE service is running." | tee -a ${LOG_FILE}
    else
        echo "$SERVICE service is not running. Please check the installation." | tee -a ${LOG_FILE}
    fi
done

# 配置 suno-api systemd 服务
SERVICE_FILE="/etc/systemd/system/suno-api.service"

cat <<EOF | sudo tee $SERVICE_FILE
[Unit]
Description=Suno API Service
After=network.target

[Service]
ExecStart=/usr/bin/npm run dev --prefix /root/suno-api
WorkingDirectory=/root/suno-api
Restart=always
RestartSec=10
User=root
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

# 重新加载 systemd 配置
log_and_execute sudo systemctl daemon-reload

# 启动并启用 suno-api 服务
log_and_execute sudo systemctl enable suno-api
log_and_execute sudo systemctl start suno-api

# 检查服务状态
if sudo systemctl is-active suno-api | grep -q "active"; then
    echo "suno-api service is running." | tee -a ${LOG_FILE}
else
    echo "suno-api service is not running. Please check the installation." | tee -a ${LOG_FILE}
fi

echo "All services have been updated and verified." | tee -a ${LOG_FILE}
